import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_page/live/live_item_widget.dart';
import 'package:xvideos/hj_page/live/live_model.dart';
import 'package:xvideos/hj_utils/sliver_delegate.dart';
import 'package:xvideos/tools_base/banner/ads_grid_view_widget.dart';
import 'package:xvideos/tools_base/loading/l_error_widget.dart';
import 'package:xvideos/tools_base/loading/loading_center_widget.dart';
import 'package:xvideos/tools_base/refresh/pull_refresh.dart';
import 'package:xvideos/tools_base/widget/net_image_widget.dart';

import '../video/video_full_page.dart';
import 'live_detail_logic.dart';

//直播详情页
class LiveDetailPage extends StatefulWidget {
  final LiveAnchor? anchor;
  const LiveDetailPage({Key? key, this.anchor}) : super(key: key);

  @override
  State<LiveDetailPage> createState() => _LiveDetailPageState();
}

class _LiveDetailPageState extends State<LiveDetailPage> {
  late LiveDetailLogic logic;

  @override
  void initState() {
    super.initState();
    logic = Get.put(
      LiveDetailLogic(anchor: widget.anchor),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(child: GetBuilder<LiveDetailLogic>(
        builder: (_) {
          return Stack(
            children: [
              //1.页面框架
              _buildLivePage(),
              //2.返回按钮
              Positioned(
                left: 10,
                top: 10,
                child: _buildBackAction(),
              )
            ],
          );
        },
      )),
    );
  }

  //页面框架
  _buildLivePage() {
    return pullYsRefresh(
        enablePullDown: false,
        onInit: (controller) => logic.controller = controller,
        onLoading: (controller) => logic.loadMoreData(),
        child: CustomScrollView(
          slivers: [
            SliverPersistentHeader(
              pinned: true,
              delegate: MySliverDelegate(
                forceRefresh: true,
                maxHeight: Get.width / (logic.aspectRatio ?? 1),
                minHeight: logic.isVerticalVideo ? Get.width / (logic.aspectRatio ?? 1) : Get.height / 3 - 60,
                child: ClipRRect(
                  //部分机型会超出比例，裁剪掉多余部分
                  child: Container(child: _buildVideo(), color: Colors.black),
                ),
              ),
            ),
            SliverToBoxAdapter(child: _buildAnchorInfo()),
            SliverToBoxAdapter(child: _buildAds()),
            SliverToBoxAdapter(child: SizedBox(height: 10)),
            _buildLine(),
            SliverToBoxAdapter(
              child: Container(
                padding: EdgeInsets.fromLTRB(16, 18, 16, 12),
                child: Text(
                  '热门直播',
                  style: TextStyle(fontSize: 16, color: Colors.white, fontWeight: FontWeight.w500),
                ),
              ),
            ),
            _buildRecomendList(),
            SliverToBoxAdapter(child: SizedBox(height: 18)),
            _buildLine(),
          ],
        ));
  }

  _buildVideo() {
    return GetBuilder<LiveDetailLogic>(
      id: 'player',
      builder: (controller) => Stack(
        alignment: Alignment.center,
        children: [
          if (logic.loadingUserInfo) ...[
            //1.加载用户直播权益信息
            AspectRatio(
              aspectRatio: logic.aspectRatio ?? 1,
              child: _buildCover(),
            ),
            LoadingCenterWidget(),
          ] else ...[
            //2.有播放权限
            if (logic.canWatchLive) ...[
              //3.主播在线
              if (logic.anchor?.isOnline == true) ...[
                Hero(
                  tag: 'player',
                  child: AspectRatio(
                    aspectRatio: logic.aspectRatio ?? 1,
                    child: logic.initedVideoController ? VideoPlayer(logic.playerController!) : _buildCover(),
                  ),
                ),
                if (logic.initedVideoController) ...[
                  Positioned(
                    right: 12,
                    bottom: 6,
                    child: GestureDetector(
                      onTap: () async {
                        await Get.to(VideoFullPage(controller: logic.playerController!, showMenu: false));
                      },
                      child: Image.asset(
                        "full_icon.png".videoPath,
                        width: 26,
                        height: 26,
                      ),
                    ),
                  )
                ],
                Obx(
                  () => Offstage(
                    offstage: !logic.isLoading.value,
                    child: _buildLoading(),
                  ),
                ),
              ] else ...[
                _buildOfflineWidget(), //4.离线
              ]
            ] else ...[
              _buildNoPermissionWidget() //5.无权限
            ],
          ]
        ],
      ),
    );
  }

  _buildNoPermissionWidget() {
    return Container(
      color: Colors.black,
      child: Stack(
        fit: StackFit.expand,
        children: [
          _buildCover(),
          Container(
              color: Colors.black.withOpacity(.7),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '温馨提示',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.white,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  SizedBox(height: 12),
                  Text(
                    '开通直播卡全站直播骚货任选～',
                    style: TextStyle(fontSize: 12, color: Colors.white),
                  ),
                  SizedBox(height: 18),
                  GestureDetector(
                    onTap: logic.onChargeAction,
                    child: Container(
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(3),
                            gradient: LinearGradient(
                              colors: [
                                Color(0xff84A4F9),
                                Color(0xff2B5DDE),
                              ],
                            )),
                        padding: EdgeInsets.symmetric(horizontal: 8, vertical: 6),
                        child: Text(
                          '立即开通直播卡',
                          style: TextStyle(fontSize: 14, color: Colors.white),
                        )),
                  ),
                ],
              )),
        ],
      ),
    );
  }

  _buildCover() {
    return NetworkImageLoader(
      imageUrl: logic.anchor?.coverImg ?? '',
      encrypt: false,
      borderRadius: 0,
      width: Get.width,
    );
  }

  _buildOfflineWidget() {
    return Container(
      color: Colors.black,
      child: Stack(
        fit: StackFit.expand,
        children: [
          _buildCover(),
          Container(
            color: Colors.black.withOpacity(.7),
            alignment: Alignment.center,
            child: Text(
              '当前主播离线，请前往观看其她热门主播喔～',
              style: TextStyle(fontSize: 14, color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }

  _buildRecomendList() {
    return GetBuilder<LiveDetailLogic>(
      id: 'recommend',
      builder: (_) {
        if (_.loading)
          return SliverToBoxAdapter(
            child: LoadingWidget(),
          );
        if (_.recommendList.isEmpty)
          return SliverToBoxAdapter(
              child: SizedBox(
            height: 300,
            child: CErrorWidget(),
          ));
        return SliverPadding(
          padding: EdgeInsets.symmetric(horizontal: 16),
          sliver: SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 12,
              crossAxisSpacing: 7,
              childAspectRatio: 168 / 105,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                LiveAnchor anchor = logic.recommendList[index];
                return LiveItemWidget(
                  showType: 5,
                  anchor: anchor,
                  action: () => logic.onChangeLiveAction(anchor),
                );
              },
              childCount: logic.recommendList.length,
            ),
          ),
        );
      },
    );
  }

  _buildBackAction() {
    return GestureDetector(
      child: Image.asset(
        "back_circle.png".commonImgPath,
        width: 24,
      ),
      onTap: () => Get.back(),
    );
  }

  _buildLoading() {
    return LoadingCenterWidget();
  }

  _buildAnchorInfo() {
    return Padding(
      padding: EdgeInsets.fromLTRB(16, 12, 16, 0),
      child: Column(
        children: [
          Row(
            children: [
              NetworkImageLoader(
                imageUrl: logic.anchor?.coverImg ?? '',
                width: 36,
                height: 36,
                borderRadius: 18,
                encrypt: false,
              ),
              SizedBox(width: 4),
              Text(
                logic.anchor?.name ?? '',
                style: TextStyle(fontSize: 14, color: Colors.white),
              ),
            ],
          ),
          SizedBox(height: 18),
          Row(
            children: [
              Text(
                '${logic.anchor?.viewCount}人观众',
                style: TextStyle(fontSize: 12, color: Color(0xff999999)),
              ),
              Spacer(),
              GestureDetector(
                onTap: () => logic.onShareAction(),
                child: Row(
                  children: [
                    Image.asset(
                      'assets/images/live_images/live_share.png',
                      width: 24,
                    ),
                    SizedBox(width: 2),
                    Text(
                      '分享',
                      style: TextStyle(fontSize: 12, color: Color(0xff999999)),
                    ),
                  ],
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  _buildAds() {
    return AdsGridViewWidget(
      36,
      isBigStyle: false,
      isBannerStyle: false,
      padding: EdgeInsets.fromLTRB(16, 18, 0, 0),
      horCount: 5.3,
    );
  }

  _buildLine() {
    return SliverToBoxAdapter(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16),
        height: .5,
        color: Colors.black.withOpacity(.1),
      ),
    );
  }
}
